package it.uai.domainsMigrator;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

import org.apache.log4j.Logger;

public class MailController {

	private static final Logger logger = Logger.getLogger(MailController.class);

	private ArrayList<Recipient> recipients = new ArrayList<Recipient>();
	private String sender;
	private String subject;
	private String message;

	public MailController(String sender, String subject, String recipientsFile, String message) {
		
		this.sender = sender;
		this.subject = subject;
		this.message = message;

		BufferedReader br = null;

		try {

			String sCurrentLine;

			br = new BufferedReader(new FileReader(recipientsFile));

			while ((sCurrentLine = br.readLine()) != null) {
				if (!sCurrentLine.startsWith("#") & !sCurrentLine.isEmpty()) {
					String[] valori = sCurrentLine.split(",");
					Recipient dest = new Recipient();
					dest.setName(valori[0]);
					dest.setEmail(valori[1]);
					dest.setFtpHost(valori[2]);
					dest.setUsername(valori[3]);
					dest.setPassword(valori[4]);
					dest.setBasePath(valori[5]);
					recipients.add(dest);
					logger.debug("add new recipient");
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}

	}
	
	public void setConnectionParameters(String smtpHost, String smtpPort, String smtpUsername, String smtpPassword) throws AddressException, MessagingException{
		sendMail(new MailSender(smtpHost, smtpPort, smtpUsername, smtpPassword));	
	}
	
	private void sendMail(MailSender mailSender) throws AddressException, MessagingException{
		
		for (Recipient r : recipients) {
			
			mailSender.send(sender, r.getEmail(), subject, getContent(r, message));
			
		}
		
	}

	private String getContent(Recipient rec, String messaggio){
		
		String mess = messaggio;
		
		mess.replaceAll("username", rec.getUsername());
		mess.replaceAll("password", rec.getPassword());
		mess.replaceAll("ftphost", rec.getFtpHost());
		mess.replaceAll("basepath", rec.getBasePath());
		
		return mess;
		
	}
}
